<!-- 多层圆环 -->
<template>
  <div class="pie-root" :style="`height: ${height};`" :id="domId"></div>
</template>

<script>
import * as echarts from "echarts";
import { deepMerge, typeOf } from "@/utils/assist.js";

export default {
  name: "echarts-pie",
  components: {},
  props: {
    domId: {
      type: String,
      default: "echarts-pie",
    },
    height: {
      type: String,
      default: "300px",
    },
    chartsData: {
      type: Object,
      default: function () {
        return {
          xData: [],
          yData: [
            // {
            //     "name": "在建工地",
            //     "value": 1
            // },
            // {
            //     "name": "市政设施",
            //     "value": 1
            // },
            // {
            //     "name": "交通设施",
            //     "value": 1
            // },
          ],
        };
      },
    },
    myOption: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  data() {
    return {
      colorList: [
        {
          colorStart:'rgba(16,227,158)',
          colorEnd:'rgba(0,185,176)',
        },
        {
          colorStart:'transparent',
          colorEnd:'transparent',
        },
        {
          colorStart:'rgba(69,149,247)',
          colorEnd:'rgba(0,93,204)',
        },
        {
          colorStart:'transparent',
          colorEnd:'transparent',
        },
        {
          colorStart:'rgba(255,210,63)',
          colorEnd:'rgba(255,173,1)',
        },
        {
          colorStart:'transparent',
          colorEnd:'transparent',
        },
        {
          colorStart:'rgba(249,159,86)',
          colorEnd:'rgba(214,120,44)',
        },
        {
          colorStart:'transparent',
          colorEnd:'transparent',
        },
        {
          colorStart:'rgba(249,86,87)',
          colorEnd:'rgba(214,44,44)',
        },
        {
          colorStart:'transparent',
          colorEnd:'transparent',
        },
      ],
      colorList2:[],
      colorList3:[],
    };
  },
  watch: {
    chartsData: {
      handler(newVal, oldVal) {
        // console.log(newVal)
        this.$nextTick(() => {
          this.draw();
        });
        // this.draw();
      },
      deep: true,
      // immediate: true,
    },
    myOption: {
      handler(newVal, oldVal) {
        // console.log(newVal)
        this.$nextTick(() => {
          this.draw();
        });
      },
      deep: true,
      // immediate: true,
    },
  },
  methods: {
    init(){
      this.colorList2 = this.colorList.map(item => {
        if(item.colorStart == 'transparent'){
          return {
            colorStart: item.colorStart,
            colorEnd: item.colorEnd,
          }
        }else{
          return {
            colorStart: item.colorStart.slice(0, -1) + ',0.5)',
            colorEnd: item.colorEnd.slice(0, -1) + ',0.5)',
          }
        }
      })
      this.colorList3 = this.colorList.map(item => {
        if(item.colorStart == 'transparent'){
          return {
            colorStart: item.colorStart,
            colorEnd: item.colorEnd,
          }
        }else{
          return {
            colorStart: item.colorStart.slice(0, -1) + ',0.2)',
            colorEnd: item.colorEnd.slice(0, -1) + ',0.2)',
          }
        }
      })
    },
    draw() {
      // console.log(document.getElementById(this.domId))

      if (!document.getElementById(this.domId)) {
        console.warn("初始化echarts dom标签未找到");
        return;
      }
      let myChart = echarts.init(document.getElementById(this.domId));
      let option = {
        title: {

        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {

        },
        // color: ['#37FFC9', '#FFE777', '#19D6FF', '#32A1FF', '#cccccc', '#ff1111'],
        // color2: [],
        // color3: [],
        // calculable: true,
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: [
              { value: 335, name: "直接访问" },
              { value: 310, name: "邮件营销" },
              { value: 234, name: "联盟广告" },
              { value: 135, name: "视频广告" },
              { value: 1548, name: "搜索引擎" },
            ],
          },
        ],
      };

      let yData = this.chartsData.yData;
      if (yData[0] && yData[0].data) {
        option.series = [];

        yData.forEach((item, index) => {
          // 计算各个圆环间隔的长度
          let total = item.data.reduce((total, item) => {
            return total + item.value;
          }, 0);
          let intervalValue = total / 100

          // 在每一个真实数据后增加一条假数据，形成圆弧间隔效果
          let newData = []
          item.data.forEach((item2,index) => {
            // console.log(item2)
            if(item2.value){
              // value大于0才加间隔
              newData.push(item2,{
                value: intervalValue,
                name: item2.name,
              })
            }else{
              newData.push(item2,{
                // value: 0,
                name: item2.name,
              })
            }
          })

          option.series.push({
            type: "pie",
            radius : ['70%', '80%'],
            center: ["50%", "50%"],
            ...item,
            data: newData,
            label: {
              // 去掉指示文字
              normal: {
                color: 'transparent',
                show : false
              }
            },
            labelLine: {
              // 尝试去掉指示线，没有效果啊
              lineStyle:{
                color: 'transparent',
              },
              // 尝试去掉指示线，没有效果啊
              normal:{
                show: false,
                color: 'transparent',
              }
            },
            itemStyle: {
              normal: {
                color: (params) => {
                  return new echarts.graphic.LinearGradient(
                    0, 0, 0, 1,
                    [
                      {offset: 0, color: this.colorList[params.dataIndex].colorStart},
                      {offset: 1, color: this.colorList[params.dataIndex].colorEnd},
                    ]
                  )
                }
              }
            }
          });
          option.series.push({
            type: "pie",
            radius : ['60%', '70%'],
            center: ["50%", "50%"],
            ...item,
            data: newData,
            label: {
              // 去掉指示线
              normal: {
                show : false
              }
            },
            labelLine: {
              normal:{
                show:false
              }
            },
            itemStyle: {
              normal: {
                color: (params) => {
                  return new echarts.graphic.LinearGradient(
                    0, 0, 0, 1,
                    [
                      {offset: 0, color: this.colorList2[params.dataIndex].colorStart},
                      {offset: 1, color: this.colorList2[params.dataIndex].colorEnd},
                    ]
                  )
                }
              }
            }
          });
          option.series.push({
            type: "pie",
            radius : ['50%', '60%'],
            center: ["50%", "50%"],
            ...item,
            data: newData,
            label: {
              // 去掉指示线
              normal: {
                show : false
              }
            },
            labelLine: {
              normal:{
                show:false
              }
            },
            itemStyle: {
              normal: {
                color: (params) => {
                  return new echarts.graphic.LinearGradient(
                    0, 0, 0, 1,
                    [
                      {offset: 0, color: this.colorList3[params.dataIndex].colorStart},
                      {offset: 1, color: this.colorList3[params.dataIndex].colorEnd},
                    ]
                  )
                }
              }
            }
          });

          // let lengedNameWidth = 0 //lenged中name的宽度
          // for(let item2 of item.data){
          //   lengedNameWidth = Math.max(lengedNameWidth, item2.name.length*12)//根据最长的name计算宽度
          // }
          // option.legend = {
          //   orient: 'vertical',
          //   top: 'middle',
          //   right: '5%',
          //   // icon: 'rect',
          //   // itemHeight: 10, // 修改icon图形大小
          //   // itemWidth: 10, // 修改icon图形大小
          //   itemGap: 6, // 修改icon间距
          //   // formatter: 'Legend {name}',
          //   // 使用回调函数
          //   formatter: function (name) {
          //     for(let item2 of item.data){
          //       if(item2.name == name){
          //         let p
          //         if(total == 0 || !item2.value){
          //           p = 0
          //         }else{
          //           p = (item2.value/total*100).toFixed(2)
          //         }
          //         return `{name|${name}} {count|${item2.value}} {percent|${p}%}`
          //       }
          //     }
          //   },
          //   textStyle:{
          //     fontSize: '16px',//字体大小
          //     color: '#fff',//字体颜色
          //     rich: {
          //       name: {
          //         width: lengedNameWidth,
          //         color: '#333333',
          //         padding: [0, 40, 0, 0],
          //         fontSize: '16px',
          //       },
          //       count:{
          //         color: '#83878b',
          //         fontSize: '16px',
          //         padding: [0, 20, 0, 0],
          //       },
          //       percent:{
          //         color: '#83878b',
          //         fontSize: '16px',
          //       }
          //     }
          //   },
          // }
        });
      } else {
        option.series[0] = {
          name: "",
          type: "pie",
          radius : ['40%', '60%'],
          center: ["50%", "50%"],
          data: yData,
        };
      }

      option = deepMerge(option, this.myOption);
      // console.log(option)
      option && myChart.setOption(option);
      myChart.off('click');//先解绑事件，防止事件重复触发
      myChart.on('click', this.titleClick)
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    titleClick(params){
      if(params.componentType=='title'){
        this.$emit("titleClick")
      }
    }
  },
  created(){
    this.init()
  },
  mounted() {
    // console.log(document.getElementById(this.domId))
  },
};
</script>

<style lang="scss" scoped>
.pie-root {
  // height: 300px;
}
</style>
